import type { EChartsOption } from "echarts";
import {
  getMainPower,
  getMainFrequency,
  getMainVoltage,
  getMainCurrent,
  getLoadRateDetailV2,
  queryTotalElectricitySPC
} from "@/api/modules/operation";
import { PxLoading } from "px-ui";

/**
 * @description: 折线图配置
 * @param {Boolean} flag       是否为双纵坐标，默认为false，即单纵坐标
 * @param {String} unit        单位
 * @param {Array} xAxisData    横坐标
 * @param {Array} specData     第一组纵坐标 SPEC目标值
 * @param {Array} usedData     第一组纵坐标 实际值
 * @param {Array} upperData    第一组纵坐标 SPEC上限值
 * @param {Array} lowerData    第一组纵坐标 SPEC下限值
 * @param {Array} specData2    第二组纵坐标 SPEC目标值
 * @param {Array} usedData2    第二组纵坐标 实际值
 * @param {Array} upperData2   第二组纵坐标 SPEC上限值
 * @param {Array} lowerData2   第二组纵坐标 SPEC下限值
 * @param {String} seriesName  当前 series name
 * @return {*}
 */
const labelLayoutLineChartFn = (
  flag = false,
  unit: string,
  label: string,
  seriesName?: string,
  xAxisData?: Array<string>,
  specData?: Array<number>,
  usedData?: Array<number>,
  upperData?: Array<number>,
  lowerData?: Array<number>,
  specData2?: Array<number>,
  usedData2?: Array<number>,
  upperData2?: Array<number>,
  lowerData2?: Array<number>
): CommonEcharts.CommonEchartsOption => {
  function getSeriesOptionsItem(name?: string, data?: Array<number>, color?: string, yAxisIndex = 0, unit = "", smooth = false): any {
    const s = {
      name,
      unit,
      type: "line",
      symbol: "circle",
      symbolSize: 4,
      data,
      yAxisIndex,
      smooth,
      itemStyle: {
        color
      },
      lineStyle: {
        color,
        width: 1
      }
    };
    return s;
  }

  function getSeriesOptions(flag?: boolean, seriesName?: string): Array<any> {
    if (flag) {
      if (seriesName && seriesName.includes("电压")) {
        return [
          getSeriesOptionsItem("实际电压", usedData, "#3B82F6", 0, "V"),
          getSeriesOptionsItem("实际电流", usedData2, "#6f6f6f", 1, "A"),
          getSeriesOptionsItem("电压SPEC目标值", specData, "#70B602", 0, "V"),
          getSeriesOptionsItem("电压SPEC上限", upperData, "#F1999B", 0, "V"),
          getSeriesOptionsItem("电压SPEC下限", lowerData, "#F59A23", 0, "V")
        ];
      } else if (seriesName && seriesName.includes("电流")) {
        return [
          getSeriesOptionsItem("实际电压", usedData, "#3B82F6", 0, "V"),
          getSeriesOptionsItem("实际电流", usedData2, "#6f6f6f", 1, "A"),
          getSeriesOptionsItem("电流SPEC目标值", specData2, "#70B602", 1, "A"),
          getSeriesOptionsItem("电流SPEC上限", upperData2, "#F1999B", 1, "A"),
          getSeriesOptionsItem("电流SPEC下限", lowerData2, "#F59A23", 1, "A")
        ];
      } else {
        return [getSeriesOptionsItem("实际电压", usedData, "#3B82F6", 0, "V"), getSeriesOptionsItem("实际电流", usedData2, "#6f6f6f", 1, "A")];
      }
    } else {
      if (seriesName && seriesName.includes(label)) {
        return [
          getSeriesOptionsItem(`实际${label}`, usedData, "#3B82F6", 0, unit, true),
          getSeriesOptionsItem(`${label}SPEC目标值`, specData, "#70B602", 0, unit, true),
          getSeriesOptionsItem(`${label}SPEC上限`, upperData, "#F1999B", 0, unit, true),
          getSeriesOptionsItem(`${label}SPEC下限`, lowerData, "#F59A23", 0, unit, true)
        ];
      } else {
        return [getSeriesOptionsItem(`实际${label}`, usedData, "#3B82F6", 0, unit, true)];
      }
    }
  }

  function getTooltip(flag?: boolean): any {
    const tooltip = {
      trigger: "axis",
      triggerOn: "mousemove",
      hideDelay: 100,
      axisPointer: {
        type: "cross",
        axis: "x"
      }
    };
    if (flag) {
      tooltip["formatter"] = function (params) {
        let tooltipHtml = `时间：${params[0].name}`;
        params.forEach(item => {
          const { seriesName, marker, value } = item;
          let i = `<br/>${marker} ${seriesName}： ${value}`;
          if (seriesName && seriesName.includes("电压")) {
            i += " V";
          } else if (seriesName && seriesName.includes("电流")) {
            i += " A";
          }
          tooltipHtml += i;
        });
        return tooltipHtml;
      };
    }
    return tooltip;
  }

  function getYAxis(flag?: boolean): any | Array<any> {
    if (flag) {
      return [
        {
          name: "电压/V",
          type: "value"
          // nameLocation: "start",
          // alignTicks: true
        },
        {
          name: "电流/A",
          type: "value",
          nameLocation: "end",
          alignTicks: true
        }
      ];
    } else {
      return {
        name: `单位/${unit}`,
        type: "value",
        axisPointer: {
          show: true,
          type: "line",
          label: {
            show: true
          },
          lineStyle: {
            type: "dashed",
            color: "#979797"
          }
        }
      };
    }
  }

  function getCommonOptions(flag?: boolean): EChartsOption {
    const title = {
      left: -5,
      top: -6,
      subtextStyle: {
        color: "#333"
      }
    };
    const legend = { show: true };
    const grid = {
      left: 0,
      right: 16,
      top: 40,
      bottom: 0,
      containLabel: true
    };
    const xAxis: any = {
      type: "category",
      boundaryGap: false,
      data: xAxisData,
      axisPointer: {
        show: true,
        type: "line",
        label: {
          show: true
        },
        lineStyle: {
          type: "dashed",
          color: "#979797"
        }
      }
    };
    const tooltip: any = getTooltip(flag);
    const yAxis: any | Array<any> = getYAxis(flag);
    return {
      title,
      tooltip,
      legend,
      grid,
      xAxis,
      yAxis
    };
  }
  const commonOptions: EChartsOption = getCommonOptions(flag);
  const series: Array<any> = getSeriesOptions(flag, seriesName);
  const options: EChartsOption = { ...commonOptions, series };
  return options;
};

const labelLayoutLineChartFn4 = (
  type: number,
  flag = false,
  unit: string,
  label: string,
  seriesName?: string,
  xAxisData?: Array<string>,
  usedData1?: Array<number>,
  usedData2?: Array<number>,
  voltageSpec?: Array<number>,
  currentSpec?: Array<number>
): CommonEcharts.CommonEchartsOption => {
  function getSeriesOptionsItem(name?: string, data?: Array<number>, color?: string, yAxisIndex = 0, unit = "", smooth = false): any {
    const s = {
      name,
      unit,
      type: "line",
      symbol: "circle",
      symbolSize: 4,
      data,
      yAxisIndex,
      smooth,
      itemStyle: {
        color
      },
      lineStyle: {
        color,
        width: 1
      }
    };
    return s;
  }

  function getSeriesOptions(flag?: boolean, seriesName?: string): Array<any> {
    if (flag) {
      if (seriesName && seriesName.includes("电压")) {
        return [
          getSeriesOptionsItem("实际电压", usedData1, "#3B82F6", 0, "V"),
          getSeriesOptionsItem("实际电流", usedData2, "#6f6f6f", 1, "A"),
          getSeriesOptionsItem("电压 TARGET", voltageSpec.targetData, "#70B602", 0, "V"),
          getSeriesOptionsItem("电压 USL", voltageSpec.uslData, "#A600FF", 0, "V"),
          getSeriesOptionsItem("电压 UCL", voltageSpec.uclData, "#FF0000", 0, "V"),
          getSeriesOptionsItem("电压 UWL", voltageSpec.uwlData, "#FF9900", 0, "V"),
          getSeriesOptionsItem("电压 LSL", voltageSpec.lslData, "#A600FF", 0, "V"),
          getSeriesOptionsItem("电压 LCL", voltageSpec.lclData, "#FF0000", 0, "V"),
          getSeriesOptionsItem("电压 LWL", voltageSpec.lwlData, "#FF9900", 0, "V")
        ];
      } else if (seriesName && seriesName.includes("电流")) {
        return [
          getSeriesOptionsItem("实际电压", usedData1, "#3B82F6", 0, "V"),
          getSeriesOptionsItem("实际电流", usedData2, "#6f6f6f", 1, "A"),
          getSeriesOptionsItem("电流 TARGET", currentSpec.targetData, "#70B602", 1, "A"),
          getSeriesOptionsItem("电流 USL", currentSpec.uslData, "#A600FF", 1, "A"),
          getSeriesOptionsItem("电流 UCL", currentSpec.uclData, "#FF0000", 1, "A"),
          getSeriesOptionsItem("电流 UWL", currentSpec.uwlData, "#FF9900", 1, "A"),
          getSeriesOptionsItem("电流 LSL", currentSpec.lslData, "#A600FF", 1, "A"),
          getSeriesOptionsItem("电流 LCL", currentSpec.lclData, "#FF0000", 1, "A"),
          getSeriesOptionsItem("电流 LWL", currentSpec.lwlData, "#FF9900", 1, "A")
        ];
      } else {
        return [getSeriesOptionsItem("实际电压", usedData1, "#3B82F6", 0, "V"), getSeriesOptionsItem("实际电流", usedData2, "#6f6f6f", 1, "A")];
      }
    } else {
      if (seriesName && seriesName.includes(label)) {
        return [
          getSeriesOptionsItem(`实际${label}`, usedData1, "#3B82F6", 0, unit, true),
          getSeriesOptionsItem(`${label}SPEC目标值`, specData, "#70B602", 0, unit, true),
          getSeriesOptionsItem(`${label}SPEC上限`, upperData, "#F1999B", 0, unit, true),
          getSeriesOptionsItem(`${label}SPEC下限`, lowerData, "#F59A23", 0, unit, true)
        ];
      } else {
        return [getSeriesOptionsItem(`实际${label}`, usedData1, "#3B82F6", 0, unit, true)];
      }
    }
  }

  function getTooltip(flag?: boolean): any {
    const tooltip = {
      trigger: "axis",
      triggerOn: "mousemove",
      hideDelay: 100,
      axisPointer: {
        type: "cross",
        axis: "x"
      }
    };
    if (flag) {
      tooltip["formatter"] = function (params) {
        let tooltipHtml = `时间：${params[0].name}`;
        params.forEach(item => {
          const { seriesName, marker, value } = item;
          let i = `<br/>${marker} ${seriesName}： ${value}`;
          if (seriesName && seriesName.includes("电压")) {
            i += " V";
          } else if (seriesName && seriesName.includes("电流")) {
            i += " A";
          }
          tooltipHtml += i;
        });
        return tooltipHtml;
      };
    }
    return tooltip;
  }

  function getYAxis(flag?: boolean): any | Array<any> {
    if (flag) {
      return [
        {
          name: "电压/V",
          type: "value"
          // nameLocation: "start",
          // alignTicks: true
        },
        {
          name: "电流/A",
          type: "value",
          nameLocation: "end",
          alignTicks: true
        }
      ];
    } else {
      return {
        name: `单位/${unit}`,
        type: "value",
        axisPointer: {
          show: true,
          type: "line",
          label: {
            show: true
          },
          lineStyle: {
            type: "dashed",
            color: "#979797"
          }
        }
      };
    }
  }

  function getCommonOptions(flag?: boolean): EChartsOption {
    const title = {
      left: -5,
      top: -6,
      subtextStyle: {
        color: "#333"
      }
    };
    const legend = {
      show: true,
      selected: {
        实际电压: seriesName && seriesName.includes("电压") ? true : type == 3 && !seriesName ? true : false,
        实际电流: seriesName && seriesName.includes("电流") ? true : type == 4 && !seriesName ? true : false
      }
    };
    const grid = {
      left: 0,
      right: 16,
      top: 40,
      bottom: 0,
      containLabel: true
    };
    const xAxis: any = {
      type: "category",
      boundaryGap: false,
      data: xAxisData,
      axisPointer: {
        show: true,
        type: "line",
        label: {
          show: true
        },
        lineStyle: {
          type: "dashed",
          color: "#979797"
        }
      }
    };
    const tooltip: any = getTooltip(flag);
    const yAxis: any | Array<any> = getYAxis(flag);
    return {
      title,
      tooltip,
      legend,
      grid,
      xAxis,
      yAxis
    };
  }
  const commonOptions: EChartsOption = getCommonOptions(flag);
  const series: Array<any> = getSeriesOptions(flag, seriesName);
  const options: EChartsOption = { ...commonOptions, series };
  return options;
};

// SPC 线展示
const labelLayoutLineChartFn3 = (
  flag = false,
  unit: string,
  label: string,
  seriesName?: string,
  xAxisData?: Array<string>,
  usedData?: Array<number>,
  uslData?: Array<number>,
  uclData?: Array<number>,
  uwlData?: Array<number>,
  targetData?: Array<number>,
  lwlData?: Array<number>,
  lclData?: Array<number>,
  lslData?: Array<number>
): CommonEcharts.CommonEchartsOption => {
  function getSeriesOptionsItem(name?: string, data?: Array<number>, color?: string, yAxisIndex = 0, unit = "", smooth = false): any {
    const s = {
      name,
      unit,
      type: "line",
      symbol: "circle",
      symbolSize: 4,
      data,
      yAxisIndex,
      smooth,
      itemStyle: {
        color
      },
      lineStyle: {
        color,
        width: 1
      }
    };
    return s;
  }

  function getSeriesOptions(flag?: boolean, seriesName?: string): Array<any> {
    if (flag) {
      // if (seriesName && seriesName.includes("电压")) {
      //   return [
      //     getSeriesOptionsItem("实际电压", usedData, "#3B82F6", 0, "V"),
      //     getSeriesOptionsItem("实际电流", usedData2, "#6f6f6f", 1, "A"),
      //     getSeriesOptionsItem("电压SPEC目标值", specData, "#70B602", 0, "V"),
      //     getSeriesOptionsItem("电压SPEC上限", upperData, "#F1999B", 0, "V"),
      //     getSeriesOptionsItem("电压SPEC下限", lowerData, "#F59A23", 0, "V")
      //   ];
      // } else if (seriesName && seriesName.includes("电流")) {
      //   return [
      //     getSeriesOptionsItem("实际电压", usedData, "#3B82F6", 0, "V"),
      //     getSeriesOptionsItem("实际电流", usedData2, "#6f6f6f", 1, "A"),
      //     getSeriesOptionsItem("电流SPEC目标值", specData2, "#70B602", 1, "A"),
      //     getSeriesOptionsItem("电流SPEC上限", upperData2, "#F1999B", 1, "A"),
      //     getSeriesOptionsItem("电流SPEC下限", lowerData2, "#F59A23", 1, "A")
      //   ];
      // } else {
      //   return [getSeriesOptionsItem("实际电压", usedData, "#3B82F6", 0, "V"), getSeriesOptionsItem("实际电流", usedData2, "#6f6f6f", 1, "A")];
      // }
    } else {
      if (seriesName && seriesName.includes(label)) {
        return [
          getSeriesOptionsItem(`实际${label}`, usedData, "#3B82F6", 0, unit, true),
          getSeriesOptionsItem(`${label} TARGET`, targetData, "#00E272", 0, unit, true),
          getSeriesOptionsItem(`${label} USL`, uslData, "#A600FF", 0, unit, true),
          getSeriesOptionsItem(`${label} UCL`, uclData, "#FF0000", 0, unit, true),
          getSeriesOptionsItem(`${label} UWL`, uwlData, "#FF9900", 0, unit, true),

          getSeriesOptionsItem(`${label} LSL`, lslData, "#A600FF", 0, unit, true),
          getSeriesOptionsItem(`${label} LCL`, lclData, "#FF0000", 0, unit, true),
          getSeriesOptionsItem(`${label} LWL`, lwlData, "#FF9900", 0, unit, true)
        ];
      } else {
        return [getSeriesOptionsItem(`实际${label}`, usedData, "#3B82F6", 0, unit, true)];
      }
    }
  }

  function getTooltip(flag?: boolean): any {
    const tooltip = {
      trigger: "axis",
      triggerOn: "mousemove",
      hideDelay: 100,
      axisPointer: {
        type: "cross",
        axis: "x"
      }
    };
    if (flag) {
      tooltip["formatter"] = function (params) {
        let tooltipHtml = `时间：${params[0].name}`;
        params.forEach(item => {
          const { seriesName, marker, value } = item;
          let i = `<br/>${marker} ${seriesName}： ${value}`;
          if (seriesName && seriesName.includes("电压")) {
            i += " V";
          } else if (seriesName && seriesName.includes("电流")) {
            i += " A";
          }
          tooltipHtml += i;
        });
        return tooltipHtml;
      };
    }
    return tooltip;
  }

  function getYAxis(flag?: boolean): any | Array<any> {
    if (flag) {
      return [
        {
          name: "电压/V",
          type: "value"
          // nameLocation: "start",
          // alignTicks: true
        },
        {
          name: "电流/A",
          type: "value",
          nameLocation: "end",
          alignTicks: true
        }
      ];
    } else {
      return {
        name: `单位/${unit}`,
        type: "value",
        axisPointer: {
          show: true,
          type: "line",
          label: {
            show: true
          },
          lineStyle: {
            type: "dashed",
            color: "#979797"
          }
        }
      };
    }
  }

  function getCommonOptions(flag?: boolean): EChartsOption {
    const title = {
      left: -5,
      top: -6,
      subtextStyle: {
        color: "#333"
      }
    };
    const legend = { show: true };
    const grid = {
      left: 0,
      right: 16,
      top: 40,
      bottom: 0,
      containLabel: true
    };
    const xAxis: any = {
      type: "category",
      boundaryGap: false,
      data: xAxisData,
      axisPointer: {
        show: true,
        type: "line",
        label: {
          show: true
        },
        lineStyle: {
          type: "dashed",
          color: "#979797"
        }
      }
    };
    const tooltip: any = getTooltip(flag);
    const yAxis: any | Array<any> = getYAxis(flag);
    return {
      title,
      tooltip,
      legend,
      grid,
      xAxis,
      yAxis
    };
  }
  const commonOptions: EChartsOption = getCommonOptions(flag);
  const series: Array<any> = getSeriesOptions(flag, seriesName);
  const options: EChartsOption = { ...commonOptions, series };
  return options;
};

/**
 * @description: 获取某项数据
 * @param {Array} res 需要 echarts 渲染的数据（数组）
 * @param {*} key 所需获取数据的 key 默认为 hour
 * @return {*}
 */
export const formatEchartsItemData = (res?: Array<any> | null, key = "hour"): Array<string> => {
  if (!res?.length) return [];
  return res.map(item => item[key]);
};

/**
 * @description: 格式化总体供电数据（电课）
 * @param {Record} data
 * @param {*} any
 * @return {*}
 */
const formatTotalEConsumeEData = (data?: Record<string, any> | null) => {
  const { voltage, current } = data;
  if (!voltage || !current) return null;
  const { min: minVoltage = 0, max: maxVoltage = 0, target: targetVoltage = 0, hourList: hourListVoltage = [] } = voltage;
  const { min: minCurrent = 0, max: maxCurrent = 0, target: targetCurrent = 0, hourList: hourListCurrent = [] } = current;
  const xAxisData: Array<string> = formatEchartsItemData(hourListVoltage);
  const specData: Array<number> = [];
  const usedData: Array<number> = [];
  const upperData: Array<number> = [];
  const lowerData: Array<number> = [];
  const specData2: Array<number> = [];
  const usedData2: Array<number> = [];
  const upperData2: Array<number> = [];
  const lowerData2: Array<number> = [];
  // 电压
  hourListVoltage.forEach(item => {
    const { value = 0 } = item;
    usedData.push(value);
    specData.push(targetVoltage);
    upperData.push(maxVoltage);
    lowerData.push(minVoltage);
  });
  // 电流
  hourListCurrent.forEach(item => {
    const { value = 0 } = item;
    usedData2.push(value);
    specData2.push(targetCurrent);
    upperData2.push(maxCurrent);
    lowerData2.push(minCurrent);
  });
  return {
    xAxisData,
    specData,
    usedData,
    upperData,
    lowerData,
    specData2,
    usedData2,
    upperData2,
    lowerData2
  };
};

// 供电 spc
const formatTotalEConsumeEData4 = (data?: Record<string, any> | null, voltageSpecData, currentSpecData) => {
  const { voltage, current } = data;
  if (!voltage || !current) return null;
  const { hourList: hourListVoltage = [] } = voltage;
  const { hourList: hourListCurrent = [] } = current;
  const xAxisData: Array<string> = formatEchartsItemData(hourListVoltage);
  let voltageSpec = {};
  let currentSpec = {};
  const specData: Array<number> = [];
  const usedData1: Array<number> = [];
  const usedData2: Array<number> = [];
  const uslData1: Array<number> = [];
  const uslData2: Array<number> = [];
  const uclData1: Array<number> = [];
  const uclData2: Array<number> = [];
  const uwlData1: Array<number> = [];
  const uwlData2: Array<number> = [];
  const targetData1: Array<number> = [];
  const targetData2: Array<number> = [];
  const lslData1: Array<number> = [];
  const lslData2: Array<number> = [];
  const lclData1: Array<number> = [];
  const lclData2: Array<number> = [];
  const lwlData1: Array<number> = [];
  const lwlData2: Array<number> = [];
  // 电压
  hourListVoltage.forEach(item => {
    const { value = 0 } = item;
    usedData1.push(value);
    uslData1.push(voltageSpecData[0] ? voltageSpecData?.[0]?.uslValue : "-");
    uclData1.push(voltageSpecData?.[0]?.uclValue);
    uwlData1.push(voltageSpecData?.[0]?.uwlValue);
    targetData1.push(voltageSpecData?.[0]?.targetValue);
    lslData1.push(voltageSpecData?.[0]?.lslValue);
    lclData1.push(voltageSpecData?.[0]?.lclValue);
    lwlData1.push(voltageSpecData?.[0]?.lwlValue);
  });
  voltageSpec = {
    uslData: uslData1,
    uclData: uclData1,
    uwlData: uwlData1,
    targetData: targetData1,
    lslData: lslData1,
    lclData: lclData1,
    lwlData: lwlData1
  };
  // 电流
  hourListCurrent.forEach(item => {
    const { value = 0 } = item;
    usedData2.push(value);
    uslData2.push(currentSpecData[0] ? currentSpecData?.[0]?.uslValue : "-");
    uclData2.push(currentSpecData[0] ? currentSpecData?.[0]?.uclValue : "-");
    uwlData2.push(currentSpecData[0] ? currentSpecData?.[0]?.uwlValue : "-");
    targetData2.push(currentSpecData[0] ? currentSpecData?.[0]?.targetValue : "-");
    lslData2.push(currentSpecData[0] ? currentSpecData?.[0]?.lslValue : "-");
    lclData2.push(currentSpecData[0] ? currentSpecData?.[0]?.lclValue : "-");
    lwlData2.push(currentSpecData[0] ? currentSpecData?.[0]?.lwlValue : "-");
  });
  currentSpec = {
    uslData: uslData2,
    uclData: uclData2,
    uwlData: uwlData2,
    targetData: targetData2,
    lslData: lslData2,
    lclData: lclData2,
    lwlData: lwlData2
  };
  return {
    xAxisData,
    specData,
    usedData1,
    usedData2,
    voltageSpec,
    currentSpec
  };
};
/**
 * @description: 格式化总体供电数据（电课）
 * @param {Record} data
 * @param {*} any
 * @return {*}
 */
const formatTotalEConsumeEData2 = (data?: Record<string, any> | null) => {
  if (!data) return null;
  const { min = 0, max = 0, target = 0, hourList = [] } = data;
  const xAxisData: Array<string> = formatEchartsItemData(hourList);
  const specData: Array<number> = [];
  const usedData: Array<number> = [];
  const upperData: Array<number> = [];
  const lowerData: Array<number> = [];
  hourList.forEach(item => {
    const { value = 0 } = item;
    usedData.push(value);
    specData.push(target);
    upperData.push(max);
    lowerData.push(min);
  });
  return {
    xAxisData,
    specData,
    usedData,
    upperData,
    lowerData
  };
};

const formatTotalEConsumeEData3 = (data?: Record<string, any> | null, specData: any) => {
  if (!data) return null;
  const { hourList = [] } = data;
  const xAxisData: Array<string> = formatEchartsItemData(hourList);
  const usedData: Array<number> = [];
  const uslData: Array<number> = [];
  const uclData: Array<number> = [];
  const uwlData: Array<number> = [];
  const targetData: Array<number> = [];
  const lwlData: Array<number> = [];
  const lclData: Array<number> = [];
  const lslData: Array<number> = [];
  hourList.forEach(item => {
    const { value = 0 } = item;

    usedData.push(value);
    uslData.push(specData?.uslValue);
    uclData.push(specData?.uclValue);
    uwlData.push(specData?.uwlValue);
    targetData.push(specData?.targetValue);
    lslData.push(specData?.lslValue);
    lclData.push(specData?.lclValue);
    lwlData.push(specData?.lwlValue);
  });
  return {
    xAxisData,
    usedData,
    uslData,
    uclData,
    uwlData,
    targetData,
    lwlData,
    lclData,
    lslData
  };
};

/**
 * @description: 判断传入 echarts 的数据（数组）是否真的为空，即所有项目都为 null
 * @param {Array} d
 * @return {*}
 */
export const isActuallyEmpty = (d?: Array<string | number> | null): boolean => {
  if (!d || !d.length) return true;
  const flag = d.reduce((pre, cur) => {
    if (cur || cur === 0) {
      pre = false;
    }
    return pre;
  }, true);
  if (flag) {
    return true;
  }
  return false;
};

export const getLabelLayoutLineChartFn = (data: any, unit: string, seriesName?: string, flag: boolean = true) => {
  if (!data) return null;
  const { xAxisData, specData, usedData, upperData, lowerData, specData2, usedData2, upperData2, lowerData2 } = formatTotalEConsumeEData(data);
  if (
    isActuallyEmpty(xAxisData) ||
    (isActuallyEmpty(specData) &&
      isActuallyEmpty(usedData) &&
      isActuallyEmpty(upperData) &&
      isActuallyEmpty(lowerData) &&
      isActuallyEmpty(specData2) &&
      isActuallyEmpty(usedData2) &&
      isActuallyEmpty(upperData2) &&
      isActuallyEmpty(lowerData2))
  )
    return null;
  return labelLayoutLineChartFn(
    flag,
    unit,
    "",
    seriesName,
    xAxisData,
    specData,
    usedData,
    upperData,
    lowerData,
    specData2,
    usedData2,
    upperData2,
    lowerData2
  );
};

// 供电 重写
export const getLabelLayoutLineChartFn4 = (
  type,
  data: any,
  voltageSpecData,
  currentSpecData,
  unit: string,
  seriesName?: string,
  flag: boolean = true
) => {
  if (!data) return null;
  const { xAxisData, usedData1, usedData2, voltageSpec, currentSpec } = formatTotalEConsumeEData4(data, voltageSpecData, currentSpecData);
  if (isActuallyEmpty(xAxisData) || (isActuallyEmpty(usedData1) && isActuallyEmpty(usedData2))) return null;
  return labelLayoutLineChartFn4(type, flag, unit, "", seriesName, xAxisData, usedData1, usedData2, voltageSpec, currentSpec);
};

export const getLabelLayoutLineChartFn2 = (data: any, unit: string, seriesName: string, label: string) => {
  if (!data) return null;
  const { xAxisData, specData, usedData, upperData, lowerData } = formatTotalEConsumeEData2(data);
  if (
    isActuallyEmpty(xAxisData) ||
    (isActuallyEmpty(specData) && isActuallyEmpty(usedData) && isActuallyEmpty(upperData) && isActuallyEmpty(lowerData))
  )
    return null;
  return labelLayoutLineChartFn(false, unit, label, seriesName, xAxisData, specData, usedData, upperData, lowerData);
};

export const getLabelLayoutLineChartFn3 = (data: any, specData: any, unit: string, seriesName: string, label: string) => {
  if (!data) return null;
  const { xAxisData, usedData, uslData, uclData, uwlData, targetData, lwlData, lclData, lslData } = formatTotalEConsumeEData3(data, specData);

  if (isActuallyEmpty(xAxisData) || (isActuallyEmpty(usedData) && isActuallyEmpty(targetData))) return null;
  return labelLayoutLineChartFn3(
    false,
    unit,
    label,
    seriesName,
    xAxisData,
    usedData,
    uslData,
    uclData,
    uwlData,
    targetData,
    lwlData,
    lclData,
    lslData
  );
};

/**
 * @description: 获取总体供电echarts配置（电课）
 * @param {Array} res
 * @return {*}
 */
export const useLabelLayoutFn = async (
  // 1 总功率  2 频率  3 用电情况(电流电压) 3 电压 4 电流
  type: 1 | 2 | 3 | 4,
  mainKey: string,
  bian: string
): Promise<CommonEcharts.CommonEchartsOption> => {
  let serveLoading = PxLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.5)"
  });
  // 1 总功率  2 频率  3 用电情况(电流电压)
  if (!type) return null;
  // let spcConfig = await queryChildByTypeCodeAndItemValue({
  //   value: mainKey,
  //   typeCode: "ELTS"
  // });
  // let point_position = [];
  // let voltage_jobId = "",
  //   current_jobId = "";
  // if (type == 1) {
  //   let c = spcConfig.filter(v => v.itemName == "功率");
  //   point_position.push(JSON.parse(c[0].itemDesc).spc_job);
  // }
  // if (type == 2) {
  //   let c = spcConfig.filter(v => v.itemName == "频率");
  //   point_position.push(JSON.parse(c[0].itemDesc).spc_job);
  // }
  // if (type == 3 || type == 4) {
  //   let c1 = spcConfig.filter(v => v.itemName == "电压");
  //   voltage_jobId = JSON.parse(c1[0].itemDesc).spc_job;
  //   let c2 = spcConfig.filter(v => v.itemName == "电流");
  //   current_jobId = JSON.parse(c2[0].itemDesc).spc_job;
  //   point_position.push(voltage_jobId);
  //   point_position.push(current_jobId);
  // }

  // let cd = parseTime(new Date(), "{y}-{m}-{d}");
  // let spcData = await spcquerySpcAnalysis({
  //   jobIdList: point_position,
  //   // pointList: [point_position],
  //   timePeriod: "hour",
  //   startTime: cd + " 00:00:00",
  //   endTime: cd + " 23:59:59"
  // });
  // 获取当前
  switch (type) {
    case 1:
      try {
        let data = await getMainPower(mainKey);
        if (serveLoading) {
          serveLoading.close();
        }
        if (!data) return null;
        return getLabelLayoutSPCChartFn("kW", data, bian);
      } catch (error) {
        if (serveLoading) {
          serveLoading.close();
        }
      }
    case 2:
      try {
        let data = await getMainFrequency(mainKey);
        if (serveLoading) {
          serveLoading.close();
        }
        if (!data) return null;
        return getLabelLayoutSPCChartFn("Hz", data, bian);
      } catch (error) {
        if (serveLoading) {
          serveLoading.close();
        }
      }
    case 3:
      try {
        let data = await getMainVoltage(mainKey);
        if (serveLoading) {
          serveLoading.close();
        }
        if (!data) return null;
        return getLabelLayoutSPCChartFn("V", data, bian);
      } catch (error) {
        if (serveLoading) {
          serveLoading.close();
        }
      }
    case 4:
      try {
        let data = await getMainCurrent(mainKey);
        if (serveLoading) {
          serveLoading.close();
        }
        if (!data) return null;
        return getLabelLayoutSPCChartFn("A", data, bian);
      } catch (error) {
        if (serveLoading) {
          serveLoading.close();
        }
      }
  }
};
function formatDate(timestamp) {
  const date = new Date(timestamp);
  // const year = date.getFullYear();
  // const month = (date.getMonth() + 1).toString().padStart(2, "0");
  // const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  // const s = date.getSeconds().toString().padStart(2, "0");
  return `${h}:${m}`;
  //return `${year}-${month}-${day} ${h}:${m}:${s}`;
}

// function getLineData(data_s, bian) {
//   let data = [];
//   if (bian == "上单边" || bian == "双边") {
//     data.push(
//       {
//         name: "USL值",
//         yAxis: Number(data_s.uslValue),
//         lineStyle: {
//           color: "#A600FF",
//           wideh: "1",
//           type: "solide"
//         },
//         label: {
//           position: "insideEndTop",
//           formatter: `USL值${data_s.uslValue}`,
//           color: "#A600FF",
//           fontWeight: 600
//         }
//       },
//       {
//         name: "UCL值",
//         yAxis: Number(data_s.uclValue),
//         lineStyle: {
//           color: "#FF0000",
//           wideh: "1",
//           type: "dashed"
//         },
//         label: {
//           position: "insideEndTop",
//           formatter: `UCL值${data_s.uclValue}`,
//           color: "#FF0000",
//           fontWeight: 600
//         }
//       },
//       {
//         name: "UWL值",
//         yAxis: Number(data_s.uwlValue),
//         lineStyle: {
//           color: "#FF9900",
//           wideh: "1",
//           type: "dashed"
//         },
//         label: {
//           position: "insideEndTop",
//           formatter: `UWL值${data_s.uwlValue}`,
//           color: "#FF9900",
//           fontWeight: 600
//         }
//       }
//     );
//   }
//   if (bian == "下单边" || bian == "双边") {
//     data.push(
//       {
//         name: "Target值",
//         yAxis: Number(data_s.targetValue),
//         lineStyle: {
//           color: "#00E272",
//           wideh: "1",
//           type: "solide"
//         },
//         label: {
//           position: "insideEndTop",
//           formatter: `Target值${data_s.targetValue}`,
//           color: "#00E272",
//           fontWeight: 600
//         }
//       },
//       {
//         name: "LWL值",
//         yAxis: Number(data_s.lwlValue),
//         lineStyle: {
//           color: "#FF9900",
//           wideh: "1",
//           type: "dashed"
//         },
//         label: {
//           position: "insideEndTop",
//           formatter: `LWL值${data_s.lwlValue}`,
//           color: "#FF9900",
//           fontWeight: 600
//         }
//       },
//       {
//         name: "LCL值",
//         yAxis: Number(data_s.lclValue),
//         lineStyle: {
//           color: "#FF0000",
//           wideh: "1",
//           type: "dashed"
//         },
//         label: {
//           position: "insideEndTop",
//           formatter: `LCL值${data_s.lclValue}`,
//           color: "#FF0000",
//           fontWeight: 600
//         }
//       },
//       {
//         name: "LSL值",
//         yAxis: Number(data_s.lslValue),
//         lineStyle: {
//           color: "#A600FF",
//           wideh: "1",
//           type: "solide"
//         },
//         label: {
//           position: "insideEndTop",
//           formatter: `LSL值${data_s.lslValue}`,
//           color: "#A600FF",
//           fontWeight: 600
//         }
//       }
//     );
//   }
//   if (bian == "上单边") {
//     data.push({
//       name: "Target值",
//       yAxis: Number(data_s.targetValue),
//       lineStyle: {
//         color: "#00E272",
//         wideh: "1",
//         type: "solide"
//       },
//       label: {
//         position: "insideEndTop",
//         formatter: `Target值${data_s.targetValue}`,
//         color: "#00E272",
//         fontWeight: 600
//       }
//     });
//   }
//   return data;
// }
// load rate SPC 线展示
const getLabelLayoutSPCChartFn = (unit: String, spcData: Object, bian: String): CommonEcharts.CommonEchartsOption => {
  console.log("bian:", bian);
  let points = spcData.pointValues.map(v => v.value);
  // let max = Math.max(...points);
  let min = Math.min(...points);
  function getTooltip(): any {
    const tooltip = {
      trigger: "axis",
      triggerOn: "mousemove",
      hideDelay: 100,
      axisPointer: {
        type: "cross",
        axis: "x"
      }
    };

    return tooltip;
  }
  function getYAxis(): any | Array<any> {
    return {
      name: `${spcData.pointUnit || unit}`,
      type: "value",
      min: Math.floor(min - min * 0.1),
      // max: Math.ceil(max + max * 0.1),
      // interval: Math.floor(Math.ceil(max + max * 0.1) / 4),
      // min: spcData.jobId ? spcData.startValue : spcData.minValue,
      // max: spcData.jobId ? (spcData.endValue ? spcData.endValue : spcData.uslValue) : spcData.maxValue,
      axisPointer: {
        show: true,
        type: "line",
        label: {
          show: true
        },
        lineStyle: {
          type: "dashed",
          color: "#979797"
        }
      }
    };
  }

  function getCommonOptions(): EChartsOption {
    const title = {
      left: -5,
      top: -6,
      subtextStyle: {
        color: "#333"
      }
    };
    const legend = { show: true };
    const grid = {
      left: 0,
      right: 16,
      top: 40,
      bottom: 0,
      containLabel: true
    };
    const xAxis: any = {
      type: "category",
      boundaryGap: false,
      data: spcData.pointValues.map(item => formatDate(item.time)),
      // axisLabel: {
      //   rotate: 45 // 文字倾斜 45 度
      // },
      axisPointer: {
        show: true,
        type: "line",
        label: {
          show: true
        },
        lineStyle: {
          type: "dashed",
          color: "#979797"
        }
      }
    };
    const tooltip: any = getTooltip();
    const yAxis: any | Array<any> = getYAxis();

    return {
      title,
      tooltip,
      legend,
      grid,
      xAxis,
      yAxis
    };
  }
  const commonOptions: EChartsOption = getCommonOptions();

  const series: Array<any> = [
    {
      name: spcData.indicatorName,
      // data: response.panelList.filter(item => item.title == "UPW")[0].details.map(item => (item.value != null ? item.value : 0))
      //   ? response.panelList.filter(item => item.title == "UPW")[0].details.map(item => (item.value != null ? item.value : 0))
      //   : [0, 0, 0, 0, 0, 0, 0],
      data: spcData.pointValues.map(item => item.value),
      type: "line",
      connectNulls: true,
      label: { show: true }
      // markLine: spcData.jobId
      //   ? {
      //     symbol: "none",
      //     data: getLineData(spcData, bian)
      //   }
      //   : undefined
    }
  ];
  const options: EChartsOption = { ...commonOptions, series };
  return options;
};

// 总用电量 SPC 线展示
const getLabelLayoutSPCChartFn_totalEle = (unit: String, spcData: Array<any>, bian: String): CommonEcharts.CommonEchartsOption => {
  console.log("bian：", bian);
  function getTooltip(): any {
    const tooltip = {
      trigger: "axis",
      triggerOn: "mousemove",
      hideDelay: 100,
      axisPointer: {
        type: "cross",
        axis: "x"
      }
    };

    return tooltip;
  }
  function getYAxis(): any | Array<any> {
    return {
      name: `${unit}`,
      type: "value",
      // min: Math.min(...spcData.map(item => item.startValue)),
      // max: Math.max(...spcData.map(item => item.endValue))
      //   ? Math.max(...spcData.map(item => item.endValue))
      //   : Math.max(...spcData.map(item => item.uslValue)),
      axisPointer: {
        show: true,
        type: "line",
        label: {
          show: true
        },
        lineStyle: {
          type: "dashed",
          color: "#979797"
        }
      }
    };
  }

  function getCommonOptions(): EChartsOption {
    const title = {
      left: -5,
      top: -6,
      subtextStyle: {
        color: "#333"
      }
    };
    const legend = { show: true };
    const grid = {
      left: 0,
      right: 16,
      top: 40,
      bottom: 0,
      containLabel: true
    };
    const xAxis: any = {
      type: "category",
      boundaryGap: false,
      data: spcData[0].pointValues.map(item => formatDate(item.time)),
      // axisLabel: {
      //   rotate: 45 // 文字倾斜 45 度
      // },
      axisPointer: {
        show: true,
        type: "line",
        label: {
          show: true
        },
        lineStyle: {
          type: "dashed",
          color: "#979797"
        }
      }
    };
    const tooltip: any = getTooltip();
    const yAxis: any | Array<any> = getYAxis();

    return {
      title,
      tooltip,
      legend,
      grid,
      xAxis,
      yAxis
    };
  }
  const commonOptions: EChartsOption = getCommonOptions();
  // const series: Array<any> = [
  //   {
  //     name: spcData.indicatorName,
  //     // data: response.panelList.filter(item => item.title == "UPW")[0].details.map(item => (item.value != null ? item.value : 0))
  //     //   ? response.panelList.filter(item => item.title == "UPW")[0].details.map(item => (item.value != null ? item.value : 0))
  //     //   : [0, 0, 0, 0, 0, 0, 0],
  //     data: spcData.pointValues.map(item => item.value),
  //     type: "line",
  //     markLine: {
  //       symbol: "none",
  //       data: getLineData(bian)
  //     }
  //   }
  // ];

  function getSeriesOptions(): Array<any> {
    let list = [];
    spcData.forEach(v => {
      // spc code ELTSKB01US01AV01 fab 用电  ELTSKB01US01AV02厂务用电  ELTSKB01US01AV03总用电
      list.push({
        name: v.indicatorName,
        unit: "",
        type: "line",
        symbol: "circle",
        symbolSize: 4,
        data: v.pointValues.map(item => item.value),
        // yAxisIndex: i,
        smooth: false,
        connectNulls: true,
        itemStyle: {
          color: v.dictItemValue == "ELTSKB01US01AV01" ? "#4C9CFF" : v.dictItemValue == "ELTSKB01US01AV02" ? "#34D399" : "#FFD360"
        },
        lineStyle: {
          color: v.dictItemValue == "ELTSKB01US01AV01" ? "#4C9CFF" : v.dictItemValue == "ELTSKB01US01AV02" ? "#34D399" : "#FFD360",
          width: 1
        }
        // markLine: {
        //   symbol: "none",
        //   data: v.spcCode == "ELTSKB01US01AV03" ? getLineData(v, bian) : null
        // }
      });
    });
    return list;
  }
  const options: EChartsOption = { ...commonOptions, series: getSeriesOptions() };
  return options;
};

export const useLabelLayoutFn_rate = async (mainKey: string, bian: string): Promise<CommonEcharts.CommonEchartsOption> => {
  let serveLoading = PxLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.5)"
  });
  try {
    let data = await getLoadRateDetailV2(mainKey);
    if (serveLoading) {
      serveLoading.close();
    }
    if (!data) return null;
    return getLabelLayoutSPCChartFn("%", data, bian);
  } catch (error) {
    if (serveLoading) {
      serveLoading.close();
    }
  }
};

export const useLabelLayoutFn_totalEle = async (bian: string): Promise<CommonEcharts.CommonEchartsOption> => {
  let serveLoading = PxLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.5)"
  });
  try {
    let data = await queryTotalElectricitySPC();
    if (serveLoading) {
      serveLoading.close();
    }
    if (!data || !data.length) return null;
    return getLabelLayoutSPCChartFn_totalEle(data[0].pointUnit || "kWh", data, bian);
  } catch (error) {
    if (serveLoading) {
      serveLoading.close();
    }
  }
};
